package org.lib.authservice.user;

import java.security.Principal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.bouncycastle.util.Iterable;
import org.lib.authservice.user.dao.RoleDAO;
import org.lib.authservice.user.dao.UserDAO;
import org.lib.authservice.user.dto.AddUserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import lombok.extern.slf4j.Slf4j;

/**
 * 用户接口：临时使用
 * @author ben
 * @date 2021-10-21 15:16:23 CST
 */
@RestController
@RequestMapping(value="/user")
@Slf4j
public class UserController {
	
	@Autowired
	private UserDAO userDao;

	@Autowired
	private RoleDAO roleDao;
	
	@Autowired
	private PasswordEncoder passwordEncoder;
	
	/**
	 * 添加用户
	 * @author ben
	 * @date 2021-10-21 15:58:20 CST
	 * @param dto
	 * @return
	 */
	@PostMapping(value="/add")
	public Long add(@RequestBody AddUserDTO dto) {
		User u = new User();
		List<Role> rlList = new ArrayList<>();
		u.setAuthorities(rlList);
		
		// 查找角色：不存在就返回错误
		Set<String> roles = dto.getRoles();
		if (!CollectionUtils.isEmpty(roles)) {
			// 非空，检查每一个
			Iterator<String> it = roles.iterator();
			while (it.hasNext()) {
				String name = it.next();
				if (!name.toUpperCase().startsWith(Role.PREFIX)) {
					// 不是以 ROLE_ 开头
					name = Role.PREFIX + name;
				}
				// 检查角色是否存在
				Role rl = roleDao.findByName(name);
				if (rl == null) {
					log.error("角色不存在，添加用户失败");
					return null;
				} else {
					rlList.add(rl);
				}
			}
		}
		
		u.setUsername(dto.getUsername());
		u.setPassword(passwordEncoder.encode(dto.getPassword()));
		
		// 添加
		userDao.save(u);
		Long id = u.getId();
		log.info("添加用户：id={}", id);
		
		return id;
	}
	
	/**
	 * 验证token：其它服务调用
	 * 原理是什么？TODO
	 * @author ben
	 * @date 2021-10-21 20:15:12 CST
	 * @param principal
	 * @return
	 */
	@GetMapping(value = "current")
	public Principal getUser(Principal principal) {
		return principal;
	}

}
